package com.chexiehui.jc.ui.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.InputFilter;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.aries.ui.view.radius.RadiusTextView;
import com.aries.ui.widget.action.sheet.UIActionSheetDialog;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.AppApplication;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.filter.EmojiFilter;
import com.chexiehui.jc.entity.BaiDuLocationInfo;
import com.chexiehui.jc.entity.ForumInfo;
import com.chexiehui.jc.event.PostAddEvent;
import com.chexiehui.jc.mvp.forum.ForumDynamicPostCovenant;
import com.chexiehui.jc.mvp.forum.ForumDynamicPostPresenter;
import com.chexiehui.jc.utils.AliossUtil;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.GlideEngine;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.utils.SoftKeyboardFixerForFullscreen;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.style.PictureWindowAnimationStyle;
import com.luck.picture.lib.tools.LocalMediaUtils;
import com.sendtion.xrichtext.RichTextEditor;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

/**
 * 动态发布
 */
public class ForumDynamicPostActivity extends BaseMvpActivity<ForumDynamicPostPresenter> implements ForumDynamicPostCovenant.View {

    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.rte_rich_content)
    RichTextEditor rteRichContent;
    @BindView(R.id.tv_choose_forum)
    TextView tvChooseForum;
    @BindView(R.id.rtv_forum_name)
    RadiusTextView rtvForumName;
    @BindView(R.id.tv_choose_image)
    TextView tvChooseImage;
    private ForumInfo chooseForumInfo;
    private BaiDuLocationInfo baiDuLocationInfo;
    private String postPhotos;
    private String postContent;
    private boolean isFinishToBottom;

    @Override
    protected boolean isFinishToBottom() {
        return isFinishToBottom;
    }

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("动态")
                .setDividerVisible(false)
                .setRightText("发布")
                .setOnRightTextClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        getEditData();
                        mvpPresenter.addPost();
                    }
                });
    }

    @Override
    protected void beforeSetView() {
        Bundle bundle = getIntent().getExtras();
        if(bundle != null){
            chooseForumInfo = (ForumInfo) bundle.getSerializable("forumInfo");
            isFinishToBottom = bundle.getBoolean("isFinishToBottom", false);
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_forum_dynamic_post;
    }

    @Override
    protected void initView(Bundle var1) {
        SoftKeyboardFixerForFullscreen.assistActivity(this);
        baiDuLocationInfo = new BaiDuLocationInfo();
        //设置Emoji头像不让输入
        etTitle.setFilters(new InputFilter[]{new EmojiFilter()});
        requestAppPermissions();
        if (chooseForumInfo != null) {
            rtvForumName.setVisibility(View.VISIBLE);
            rtvForumName.setText("#" + chooseForumInfo.getName());
        }
    }

    @OnClick({R.id.tv_choose_forum, R.id.rtv_forum_name, R.id.tv_choose_image})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_choose_forum:
            case R.id.rtv_forum_name:
                showChooseForumDialog();
                break;
            case R.id.tv_choose_image:
                applyPhotoPermission(100);
                break;
        }
    }

    private void getEditData() {
        StringBuilder content = new StringBuilder();
        StringBuilder photos = new StringBuilder();
        try {
            List<RichTextEditor.EditData> editList = rteRichContent.buildEditData();
            for (RichTextEditor.EditData itemData : editList) {
                if (itemData.inputStr != null) {
                    content.append(StringUtils.isTrimEmpty(itemData.inputStr) ? "" : itemData.inputStr);
                } else if (itemData.imagePath != null) {
                    photos.append(itemData.imagePath).append(",");
//                    content.append(String.format(getStringSource(R.string.post_img), itemData.imagePath));
                    content.append("<img src=\"").append(itemData.imagePath).append("\" style=\"max-width:100%;height: auto;width: 100%\"/>");
                    //"<img src=\"").append(itemData.imagePath).append("\"/>")
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        LogUtils.e(content.toString());
        postContent = content.toString();
        postPhotos = photos.toString();
        if(!StringUtils.isTrimEmpty(postPhotos)){
            postPhotos = postPhotos.substring(0, postPhotos.lastIndexOf(","));
        }
    }

    private void showChooseForumDialog(){
        UIActionSheetDialog dialog = new UIActionSheetDialog.ListIOSBuilder(mContext)
                .addItems(new String[]{"车系论坛", "地区论坛", "主题论坛"})
                .setTitle("选择论坛类型")
                .setOnItemClickListener((dialog1, itemView, position) -> {
                    startActivityForResult(ChooseForumActivity.class, 200,
                            new BundleBuilder().putInt("chooseType", position).create());
                })
                .create();
        dialog.show();
    }

    private void requestAppPermissions() {
        AndPermission.with(this)
                .permission(Permission.LOCATION, Permission.STORAGE)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @android.support.annotation.NonNull List<String> grantPermissions) {
                        if (!AppApplication.getInstances().getLocationService().isStart()) {
                            AppApplication.getInstances().getLocationService().start();
                        }
                        AppApplication.getInstances().getLocationService().registerListener(mListener);
                    }

                    @Override
                    public void onFailed(int requestCode, @android.support.annotation.NonNull List<String> deniedPermissions) {
                        if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                            AndPermission.defaultSettingDialog(mContext, Constants.REQUEST_CODE_LOACTION).show();
                        } else {
                            showToast(getStringSource(R.string.app_name) + "需要您授权位置服务和访问文件的权限");
                        }
                    }
                })
                .requestCode(Constants.REQUEST_CODE_CARAME)
                .rationale((requestCode, rationale) -> AndPermission.rationaleDialog(mContext, rationale).show()).start();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                BDLocation location = (BDLocation) msg.obj;
                baiDuLocationInfo.setCity(location.getCity());
                baiDuLocationInfo.setLat(location.getLatitude());
                baiDuLocationInfo.setLng(location.getLongitude());
            }
        }
    };

    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                LogUtils.e("home-----------------:" + location.getAddrStr());
                if(!StringUtils.isTrimEmpty(location.getCity())){
                    Message msg = new Message();
                    msg.obj = location;
                    msg.what = 0;
                    handler.sendMessage(msg);
                }
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {
            super.onConnectHotSpotMessage(s, i);
        }

        @Override
        public void onLocDiagnosticMessage(int locType, int diagnosticType, String diagnosticMessage) {
            super.onLocDiagnosticMessage(locType, diagnosticType, diagnosticMessage);
        }
    };

    @Override
    protected void onDestroy() {
        handler.removeCallbacksAndMessages(null);
        handler = null;
        AppApplication.getInstances().getLocationService().unregisterListener(mListener);
        mListener = null;
        super.onDestroy();
    }

    private void applyPhotoPermission(final int code) {
        AndPermission.with(this)
                .permission(Permission.CAMERA, Permission.STORAGE)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        PictureWindowAnimationStyle windowAnimationStyle = new PictureWindowAnimationStyle();
                        windowAnimationStyle.ofAllAnimation(R.anim.picture_anim_up_in, R.anim.picture_anim_down_out);
                        // 进入相册 以下是例子：不需要的api可以不写
                        PictureSelector.create(mContext)
                                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                                .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                                .theme(R.style.picture_QQ_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style v2.3.3后 建议使用setPictureStyle()动态方式
                                .setPictureWindowAnimationStyle(windowAnimationStyle)// 自定义相册启动退出动画
                                .imageSpanCount(4)// 每行显示个数
                                .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回
                                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                                .isOriginalImageControl(false)// 是否显示原图控制按钮，如果设置为true则用户可以自由选择是否使用原图，压缩、裁剪功能将会失效
                                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                                .isSingleDirectReturn(true)// 单选模式下是否直接返回，PictureConfig.SINGLE模式下有效
                                .previewImage(true)// 是否可预览图片
                                .isCamera(true)// 是否显示拍照按钮
                                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                                .enableCrop(false)// 是否裁剪
                                .showCropFrame(true)
                                .freeStyleCropEnabled(false)
                                .scaleEnabled(false)
                                .showCropGrid(false)
                                .showCropFrame(true)
                                .compress(true)// 是否压缩
                                .compressQuality(90)// 图片压缩后输出质量 0~ 100
                                .synOrAsy(false)//同步false或异步true 压缩 默认同步
                                .queryMaxFileSize(20)// 只查多少M以内的图片、视频、音频  单位M
                                .isGif(false)// 是否显示gif图片
                                .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                                .minimumCompressSize(100)// 小于100kb的图片不压缩
                                .recordVideoSecond(60)//录制视频秒数 默认60s
                                .forResult(code);//结果回调onActivityResult code*/
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                            AndPermission.defaultSettingDialog(mContext, Constants.REQUEST_CODE_CARAME).show();
                        } else {
                            showToast(getStringSource(R.string.app_name) + "需要您授权打开相机和相册的权限");
                        }
                    }
                })
                .requestCode(Constants.REQUEST_CODE_CARAME)
                .rationale((requestCode, rationale) -> AndPermission.rationaleDialog(mContext, rationale).show()).start();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 100:{
                List<LocalMedia> selectedPhotoList = PictureSelector.obtainMultipleResult(data);
                if (selectedPhotoList.size() > 0) {
                    String path = LocalMediaUtils.getLocalPath(selectedPhotoList.get(0));
                    mvpPresenter.uploadImage(path);
                }
            }
            break;
            case 200:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        chooseForumInfo = (ForumInfo) data.getSerializableExtra("forumInfo");
                        if (chooseForumInfo != null) {
                            rtvForumName.setVisibility(View.VISIBLE);
                            rtvForumName.setText("#" + chooseForumInfo.getName());
                        }
                    }
                }
                break;
        }
    }

    @Override
    protected ForumDynamicPostPresenter createPresenter() {
        return new ForumDynamicPostPresenter(this);
    }

    @Override
    public void onUploadImageSuccess(BaseModel<String> successResult) {
        rteRichContent.insertImage(AliossUtil.getEndPointFileUrl(successResult.getData()));
    }

    @Override
    public void onUploadImageFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public void onAddPostSuccess(BaseModel<Object> successResult) {
        showToast(successResult.getResultInfo());
        EventBus.getDefault().post(new PostAddEvent());
        onBackPressed();
    }

    @Override
    public void onAddPostFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Override
    public String getPostTitle() {
        return etTitle.getText().toString().trim();
    }

    @Override
    public String getPostContent() {
        return postContent;
    }

    @Override
    public String getPostForum() {
        return chooseForumInfo != null ? chooseForumInfo.getId() : "";
    }

    @Override
    public String getPostPhotos() {
        return postPhotos != null ? postPhotos : "";
    }

    @Override
    public String getPostLat() {
        return baiDuLocationInfo != null ? baiDuLocationInfo.getLat() + "" : "";
    }

    @Override
    public String getPostLng() {
        return baiDuLocationInfo != null ? baiDuLocationInfo.getLng() + "" : "";
    }

    @Override
    public String getPostCity() {
        return baiDuLocationInfo != null ? baiDuLocationInfo.getCity() : "";
    }
}
